package com.rapid.maintenance.base;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import androidx.annotation.CallSuper;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.util.Pair;

import com.rapid.maintenance.R;
import com.rapid.maintenance.utils.NotchScreenUtil;
import com.rapid.maintenance.utils.UIUtils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 *
 */
public abstract class BaseActivity extends RxAppCompatActivity {
    @BindView(R.id.all_title_id)
    AppCompatTextView title;//标题
    @BindView(R.id.all_title_right)
    AppCompatTextView titleRight;//标题栏右文字
    @BindView(R.id.all_main_toolbar)
    Toolbar toolbar;//标题栏toolbar
    @BindView(R.id.status_bar)
    View statusBar;//系统栏占位view
    private Unbinder unbinder;//控件注入生成的unbinder。

    private View loadingView;//显示加载状态的控件
    private int displayHeight;

    public View getStatusBar() {
        return statusBar;
    }

    /**
     * 为本页添加实际的contentView
     *
     * @param idRes layoutId
     * @hide
     */
    private void setView(int idRes) {
        View view = LayoutInflater.from(this).inflate(idRes, null);
        ((FrameLayout) findViewById(R.id.layout_content)).addView(view);
        if (displayHeight != 0 && displayHeight > UIUtils.getStatusBarHeight(this)) {//当刘海屏的高度大于系统栏高度的时候
            ViewGroup.LayoutParams lp = view.getLayoutParams();
            if (lp instanceof ViewGroup.MarginLayoutParams) {
                ((ViewGroup.MarginLayoutParams) lp).topMargin = ((ViewGroup.MarginLayoutParams) lp).topMargin + displayHeight - UIUtils.getStatusBarHeight(this);
                view.setLayoutParams(lp);
            }
        }
    }

    protected void setStatusBarColor(int statusBarColor) {
        statusBar.setBackgroundColor(statusBarColor);
    }

    protected void setToolBarColor(int toolBarColor) {
        toolbar.setBackgroundColor(toolBarColor);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_base);
        initDisplayCutout();
        initializationData(getIntent());
        createPage();
    }

    protected void initDisplayCutout() {

        displayHeight = NotchScreenUtil.getNotch(this);
        if (!hasStatusBar()) {
            findViewById(android.R.id.content).setPadding(0, displayHeight, 0, 0);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //非默认值
        if (newConfig.fontScale != 1) {//当用户修改字体大小为非默认值
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {//还原字体大小
        Resources res = super.getResources();
        //非默认值
        if (res.getConfiguration().fontScale != 1) {
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    /**
     * 自定义生命周期
     * 页面创建
     */

    protected void createPage() {
        initPage();
    }

    /**
     * 自定义生命周期
     * 页面初始化
     */
    protected void initPage() {
        setView(provideRootLayout());
        if (isUseEventBus()) {
            EventBus.getDefault().register(this);//注册eventBus
        }
        unbinder = ButterKnife.bind(this);//注入views
        UIUtils.settingCommonStatusBar(this);
        if (hasStatusBar()) {//判断页面是否应该占满屏幕，否则用statusBar填充系统状态栏大小
            statusBar.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Math.max(displayHeight, UIUtils.getStatusBarHeight(this))));
        }
        if (!hasToolBar()) {//判断是否有标题栏
            findViewById(R.id.title_view_divide).setVisibility(View.GONE);
            toolbar.setVisibility(View.GONE);
        } else setNavigation(R.drawable.ic_back);//默认标题栏左边为返回键

        init();
    }

    /**
     * 自定义生命周期
     * 初始化intent数据
     */
    protected void initializationData(Intent intent) {

    }

    /**
     * @return 是否注册eventBus
     */
    protected boolean isUseEventBus() {
        return false;
    }

    /**
     * @see #setNavigation(int, View.OnClickListener)
     */
    protected void setNavigation(View.OnClickListener listener) {
        setNavigation(R.drawable.ic_back, listener);
    }

    /**
     * @see #setNavigation(int, View.OnClickListener)
     */
    protected void setNavigation(@DrawableRes int icon) {
        setNavigation(icon, v -> {
            onBackPressed();
            UIUtils.hideSoftInput(this, getWindow().getDecorView().getWindowToken());
        });
    }

    /**
     * 设置标题栏左边交互
     *
     * @param icon            标题栏左边展示的图标
     * @param onClickListener 标题栏左边的点击事件
     */
    protected void setNavigation(@DrawableRes int icon, View.OnClickListener onClickListener) {
        if (!hasToolBar()) return;
        toolbar.setNavigationIcon(icon);
        toolbar.setNavigationOnClickListener(onClickListener);
    }

    /**
     * 对触屏事件做拦截 判断是否需要展示显示虚拟键盘
     */
    @CallSuper
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (UIUtils.isShouldHideInput(getCurrentFocus(), event)) {
            UIUtils.hideSoftInput(this, getWindow().getDecorView().getWindowToken());
        }
        return super.onTouchEvent(event);
    }

    @CallSuper
    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();//解绑控件 释放内存
        }
        if (isUseEventBus()) {
            if (EventBus.getDefault().isRegistered(this)) {//判断是否有注册eventBus 有则解绑
                EventBus.getDefault().unregister(this);
            }
        }
        super.onDestroy();
    }

    /**
     * 设置toolbar右侧图片menu
     *
     * @param menu            右侧menu图片id
     * @param onClickListener 右侧菜单点击事件
     */
    protected void setMenu(@DrawableRes int menu, View.OnClickListener onClickListener) {
        titleRight.setVisibility(View.VISIBLE);
        titleRight.setBackgroundResource(menu);
        titleRight.setBackgroundDrawable(getResources().getDrawable(menu));
        titleRight.setOnClickListener(onClickListener);
    }

    /**
     * 设置toolbar右侧文字menu
     *
     * @param textMenu 右侧menu String id
     */
    protected void setTextMenu(@StringRes int textMenu) {
        titleRight.setText(textMenu);
    }

    /**
     * 设置toolbar右侧文字menu
     *
     * @param menu            右侧menu String
     * @param onClickListener 右侧菜单点击事件
     */
    protected void setTextMenu(CharSequence menu, View.OnClickListener onClickListener) {
        titleRight.setVisibility(View.VISIBLE);
        titleRight.setText(menu);
        titleRight.setOnClickListener(onClickListener);
    }

    /**
     * 设置toolbar右侧文字menu
     *
     * @param menuTextId      右侧menu String id
     * @param onClickListener 右侧菜单点击事件
     */
    protected void setTextMenu(@StringRes int menuTextId, View.OnClickListener onClickListener) {
        titleRight.setVisibility(View.VISIBLE);
        titleRight.setText(menuTextId);
        titleRight.setOnClickListener(onClickListener);
    }


    protected Toolbar getToolbar() {
        return toolbar;
    }

    /**
     * 页面开始加载 调用后必须调用{@link #loadingComplete()}
     */
    protected void loadingStart() {
        ViewStub view = findViewById(R.id.load_stub);
        if (view != null) {
            loadingView = view.inflate();
            loadingView.bringToFront();
        } else {
            loadingView.setVisibility(View.VISIBLE);
            loadingView.bringToFront();
        }
    }

    /**
     * 判断页面是否在加载
     *
     * @see #loadingStart()
     * @see #loadingComplete()
     */
    protected boolean isLoading() {
        return loadingView != null && loadingView.getVisibility() == View.VISIBLE;
    }

    /**
     * 页面加载结束
     */
    protected void loadingComplete() {
        if (loadingView != null)
            loadingView.setVisibility(View.GONE);
    }

    /**
     * 设置页面标题
     */
    public void setTitle(CharSequence msg) {
        title.setText(msg);
    }

    /**
     * 设置页面标题
     */
    public void setTitle(int titleId) {
        title.setText(titleId);
    }

    /**
     * @return 页面是否需要标题栏
     */
    protected boolean hasToolBar() {
        return true;
    }

    /**
     * @return 是否需要状态栏
     */
    protected boolean hasStatusBar() {
        return true;
    }

    /**
     * @return 布局id
     */
    protected abstract @LayoutRes
    int provideRootLayout();

    /**
     * 初始化数据及交互
     */
    protected abstract void init();

    /**
     * 页面跳转
     *
     * @param clz activity.class
     */
    public void startActivity(Class<? extends Activity> clz) {
        startActivity(clz, new Intent());
    }

    public void startActivityForResult(Class<? extends Activity> clz, int requestCode) {
        startActivityForResult(new Intent(this, clz), requestCode);
    }

    //启动页面
    public void startActivity(Class<? extends Activity> clz, int requestCode) {
        Intent intent = new Intent(this, clz);
        startActivityForResult(intent, requestCode);
    }

    /**
     * 携带数据的页面跳转
     *
     * @param clz    activity.class
     * @param intent data
     */
    public void startActivity(Class<? extends Activity> clz, @NonNull Intent intent) {
        intent.setClass(this, clz);
        startActivity(intent);
    }

    @SafeVarargs
    public final <T extends Activity> void startActivity(Class<T> aClass, Pair<View, String>... pairs) {
        ActivityOptionsCompat aoc = ActivityOptionsCompat.makeSceneTransitionAnimation(this, pairs);
        startActivity(aClass, aoc.toBundle());
    }

    @SuppressWarnings("unchecked")
    public void startActivityWithShareTitle(Class<? extends Activity> clz) {

        Pair<View, String> toolbar = Pair.create(getToolbar(), "all_main_toolbar");
        Pair<View, String> statusbar = Pair.create(getStatusBar(), "status_bar");
        ActivityOptionsCompat aoc = ActivityOptionsCompat.makeSceneTransitionAnimation(this, toolbar, statusbar);
        startActivity(clz, aoc.toBundle());
    }

    /**
     * 携带数据的页面跳转
     *
     * @param clz    activity.class
     * @param bundle data
     */
    public void startActivity(Class<? extends Activity> clz, @Nullable Bundle bundle) {
        startActivity(new Intent(this, clz), bundle);
    }
}
